<template>
  <div>
    <slot>
      <p class="text-sm">
        {{ showTime }}
      </p>
    </slot>
  </div>
</template>

<script>
import dayjs from './utils'
// 倒计时结束
const EMITS_FINISH = 'finish'
// 倒计时改变
const EMITS_CHANGE = 'change'
const INTERVAL_COUNT = 1000
</script>
<script setup>
import { watch, computed, onUnmounted, ref } from 'vue'

const props = defineProps({
  // 倒计时长(毫秒单位)
  time: {
    type: Number,
    required: true
  },
  format: {
    type: String,
    default: 'HH:mm:ss'
  }
})
const emits = defineEmits([EMITS_FINISH, EMITS_CHANGE])

// 组件销毁时,关闭倒计时
onUnmounted(() => {
  close()
})
// 倒计时
let interval = null
// 倒计时时长
const duration = ref(0)
const start = () => {
  close()
  interval = setInterval(() => {
    durationFn()
  }, INTERVAL_COUNT)
}
const durationFn = () => {
  duration.value -= INTERVAL_COUNT
  //  倒计时更改了...
  emits(EMITS_CHANGE)
  if (duration.value <= 0) {
    duration.value = 0
    // 倒计时走完了...
    emits(EMITS_FINISH)
  }
}
// 关闭倒计时
const close = () => {
  if (interval) {
    clearInterval(interval)
  }
}
// 处理展示时间
const showTime = computed(() => {
  return dayjs.duration(duration.value).format(props.format)
})
// 监听持续展示时长
watch(
  () => props.time,
  (val) => {
    duration.value = val
    start()
  },
  {
    immediate: true
  }
)
</script>

<style lang="scss" scoped></style>
